<template>
  <el-breadcrumb separator="/">
    <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
    <el-breadcrumb-item>商品管理</el-breadcrumb-item>
    <el-breadcrumb-item>添加商品</el-breadcrumb-item>
  </el-breadcrumb>

  <el-card>
    <el-alert title="添加商品信息" type="info" center show-icon />

    <el-steps :active="active" align-center finish-status="success" simple style="margin-top: 20px">
      <el-step title="基本信息" />
      <el-step title="商品参数" />
      <el-step title="商品属性" />
      <el-step title="商品图片" />
      <el-step title="商品内容" />
      <el-step title="完成" />
    </el-steps>

    <el-tabs tab-position="left" v-model="active" :before-leave="tabChange">
      <el-tab-pane label="基本信息" :name="0">
        <el-form ref="formRef" label-position="top" :rules="rules" label-width="100px" :model="form">
          <el-form-item label="商品名称" prop="goods_name">
            <el-input size="large" placeholder="商品名称" v-model="form.goods_name" />
          </el-form-item>
          <el-form-item label="商品价格" prop="goods_price">
            <el-input size="large" type="number" placeholder="商品价格" v-model="form.goods_price" />
          </el-form-item>
          <el-form-item label="商品重量" prop="goods_weight">
            <el-input size="large" type="number" placeholder="商品重量" v-model="form.goods_weight" />
          </el-form-item>
          <el-form-item label="商品数量" prop="goods_number">
            <el-input size="large" type="number" placeholder="商品数量" v-model="form.goods_number" />
          </el-form-item>
          <el-form-item v-if="!route.query.id" label="商品分类" prop="goods_cat">
            <el-cascader size="large" v-model="cat" :options="categories" :props="props" @change="handleChange" />
          </el-form-item>
          <el-form-item v-if="route.query.id" label="商品分类" prop="goods_cat">
            <el-tag v-if="goodsState === 0" type="danger" size="large">未通过</el-tag>
            <el-tag v-if="goodsState === 1" type="danger" size="large">审核中</el-tag>
            <el-tag v-if="goodsState === 2" type="success" size="large">已审核</el-tag>
          </el-form-item>
        </el-form>
      </el-tab-pane>
      <el-tab-pane v-if="!route.query.id" label="商品参数" :name="1">
        <div class="attr_many" v-for="item in cateAttr.manyAttrList" :key="item.attr_id">
          <span>{{ item.attr_name }}</span>
          <div>
            <el-tag v-for="(item2, index) in item.attr_vals" :key="index" size="large">{{ item2 }}</el-tag>
          </div>
        </div>
      </el-tab-pane>
      <el-tab-pane v-if="!route.query.id" label="商品属性" :name="2">
        <div class="attr_many" v-for="item in cateAttr.onlyAttrList" :key="item.attr_id">
          <span>{{ item.attr_name }}</span>
          <div>
            <el-tag v-for="(item2, index) in item.attr_vals" :key="index" size="large">{{ item2 }}</el-tag>
          </div>
        </div>
      </el-tab-pane>
      <el-tab-pane label="商品图片" :name="3">
        <el-upload v-model:file-list="fileList" :headers="headers" action="http://127.0.0.1:8888/api/private/v1/upload"
          list-type="picture-card" :on-success="onSuccess" :on-preview="onPreview" :on-remove="onRemove">
          <el-button type="primary">点击上传</el-button>
          <template #tip>
            <div class="el-upload__tip">
              只能上传jpg/png文件，且不超过500kb
            </div>
          </template>
        </el-upload>
      </el-tab-pane>
      <el-tab-pane label="商品内容" :name="4">
        <QuillEditor ref="quillRef" v-model:content="form.goods_introduce" :options="quillOption" class="quill" />
        <el-button type="primary" style="margin-top: 10px;" @click="submit">提交</el-button>
      </el-tab-pane>
    </el-tabs>
  </el-card>

  <el-dialog class="bigPic" title="提示" v-model="previewVisible" width="50%">
    <img class="preview" :src="previewPath" alt="" />
  </el-dialog>
</template>

<script setup lang="ts">
import { ref, onMounted, reactive, getCurrentInstance } from 'vue';
import { getCategoriesApi, getAttributesApi, addGoodsApi, getGoodsById, editGoodsApi } from '@/api/goodsInfa';
import { Search, Edit, Delete } from '@element-plus/icons-vue';
import { useRouter, useRoute } from 'vue-router';
import { QuillEditor } from '@vueup/vue-quill'
import type { UploadProps, UploadUserFile } from 'element-plus'
import router from '@/router';

const route = useRoute()
const { proxy } = getCurrentInstance() as any

onMounted(() => {
  if (route.query.id) {
    getGoodsById(route.query.id).then(res => {
      console.log(res);
      form.goods_name = res.data.goods_name
      form.goods_price = res.data.goods_price
      form.goods_weight = res.data.goods_weight
      form.goods_number = res.data.goods_number
      form.goods_cat = res.data.goods_cat
      quillRef.value.setHTML(res.data.goods_introduce)
      // form.goods_introduce = res.data.goods_introduce
      fileList.value = res.data.pics.map((item: any) => {
        return {
          name: item.pics_mid,
          url: item.pics_mid_url
        }
      })
      form.attrs = res.data.attrs
      goodsState.value = res.data.goods_state
    })
  }
  getCategories()
})

const active = ref(0)
const cat = ref()
const goodsState = ref()
const form = reactive({
  goods_name: undefined,
  goods_price: undefined,
  goods_weight: undefined,
  goods_number: undefined,
  goods_cat: undefined,
  goods_introduce: undefined,
  pics: [],
  attrs: []
})
const rules = reactive({
  goods_name: [
    { required: true, message: '请输入商品名称', trigger: 'blur' },
  ],
  goods_price: [
    { required: true, message: '请输入商品价格', trigger: 'blur' },
  ],
  goods_weight: [
    { required: true, message: '请输入商品重量', trigger: 'blur' },
  ],
  goods_number: [
    { required: true, message: '请输入商品数量', trigger: 'blur' },
  ],
  goods_cat: [
    { required: true, message: '请选择商品分类', trigger: 'change' },
  ],
})

const props = reactive({
  expandTrigger: 'hover',
  value: 'cat_id',
  label: 'cat_name'
})
const handleChange = (value: any) => {
  attrId.value = value[2]
  form.goods_cat = value.join(',')
}

// 获取商品分类数据列表
const categories = ref()
const getCategories = () => {
  getCategoriesApi().then(res => {
    categories.value = res.data
  })
}
// 未选择商品分类时禁止切换tabs
const tabChange = (name: number) => {
  if (!form.goods_cat) {
    proxy.$message.error('请选择商品分类')
    return false
  }
  if (name === 1) {
    getAttributes('many')
  }
  if (name === 2) {
    getAttributes('only')
  }
}

// 获取分类参数列表
const attrId = ref()
const cateAttr = reactive({
  manyAttrList: [],
  onlyAttrList: []
})
const getAttributes = (type: string) => {
  getAttributesApi(attrId.value, { sel: type }).then(res => {
    if (type === 'many') {
      cateAttr.manyAttrList = res.data.map((item: { attr_vals: string; }) => {
        return {
          ...item,
          attr_vals: item.attr_vals.split(' ')
        }
      })
    }
    if (type === 'only') {
      cateAttr.onlyAttrList = res.data.map((item: { attr_vals: string; }) => {
        return {
          ...item,
          attr_vals: item.attr_vals.split(' ')
        }
      })
    }
  })
}

// 图片上传
const headers = {
  Authorization: sessionStorage.getItem('hmds-token')
}
const fileList = ref<UploadUserFile[]>([])
const onSuccess = (response: any) => {
  const picInfo = {
    pic: response.data.tmp_path
  }
  form.pics.push(picInfo)
  proxy.$message.success('上传成功')
}
const previewPath = ref()
const previewVisible = ref(false)
const onPreview = (file: any) => {
  previewPath.value = file.url
  previewVisible.value = true
}
const onRemove = (file: any) => {
  const filePath = file.response.data.tmp_path
  const i = form.pics.findIndex((item) => item.pic === filePath)
  form.pics.splice(i, 1)
}

// 富文本编辑器配置项
const quillRef = ref()
const quillOption = {
  modules: {
    toolbar: [
      ['bold', 'italic', 'underline', 'strike'],
      [{ 'size': ['small', false, 'large', 'huge'] }],
      [{ 'font': [] }],
      [{ 'align': [] }],
      [{ 'list': 'ordered' }, { 'list': 'bullet' }],
      [{ 'indent': '-1' }, { 'indent': '+1' }],
      [{ 'header': 1 }, { 'header': 2 }],
      ['image'],
      [{ 'direction': 'rtl' }],
      [{ 'color': [] }, { 'background': [] }]
    ]
  },
  placeholder: '请输入内容...'
}

const formRef = ref()
const submit = async () => {
  if (!formRef.value) return
  await formRef.value.validate((valid: any, fields: any) => {
    if (!valid) {
      return proxy.$message.error('请填写必要的表单项')
    }
    form.goods_introduce = quillRef.value.getHTML()
    cateAttr.manyAttrList.forEach((item: any) => {
      const newObj = {
        attr_id: item.attr_id,
        attr_value: item.attr_vals.join(' ')
      }
      form.attrs.push(newObj)
    })
    cateAttr.onlyAttrList.forEach(item => {
      const newObj = {
        attr_id: item.attr_id,
        attr_value: item.attr_vals.join(' ')
      }
      form.attrs.push(newObj)
    })

    if (route.query.id) {
      editGoodsApi(route.query.id, form).then(res => {
        proxy.$message.success('编辑成功')
        router.push('/goods')
      })
    } else {
      addGoodsApi(form).then(res => {
        proxy.$message.success('添加成功')
        router.push('/goods')
      })
    }
  })
}
</script>

<style scoped lang="scss">
.el-card {
  margin-top: 20px;
}

.el-tabs {
  margin-top: 20px;
}

.el-form-item {
  margin: 20px 0;
}

.attr_many {
  margin: 20px;

  .el-tag {
    margin-right: 20px;
  }
}

.attr_many>div {
  margin: 20px 0;
}

:deep(.quill) {
  height: 450px;
}

.preview {
  width: 100%;
}
</style>